package operator;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.operators.StreamFlatMap;
import org.apache.flink.util.Collector;

/**
 * FlatMap 算子
 */
public class FlatMapDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        // 1,2,3,4,5,6,7
        DataStreamSource<String> data = env.socketTextStream("192.168.56.10", 8888);

        /*SingleOutputStreamOperator<Integer> nums = data.flatMap((String s, Collector<Integer> collector) -> {
            String[] strs = s.split(",");
            for (String num : strs) {
                int i = Integer.parseInt(num);
                if (i % 2 == 0) {
                    collector.collect(i);
                }
            }
        }).returns(Types.INT);*/
        // 调用transform
        SingleOutputStreamOperator<Integer> nums = data.transform("MyFlatMap", Types.INT, new StreamFlatMap<>((String s, Collector<Integer> collector) -> {
            String[] words = s.split(",");
            for (String word : words) {
                int i = Integer.parseInt(word);
                if (i % 2 == 0) {
                    collector.collect(i);
                }
            }
        }));

        nums.print();

        env.execute("FlatMap Demo");
    }
}
